<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="辖区名称" prop="jurisdictionName">
        <el-input
          v-model="queryParams.jurisdictionName"
          placeholder="请输入辖区名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系人" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入联系人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系号码" prop="phone">
        <el-input
          v-model="queryParams.phone"
          placeholder="请输入联系号码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="城市" prop="cityId">
        <el-select v-model="queryParams.cityId" placeholder="请选择城市" clearable size="small">
          <el-option
            v-for="dict in cityIdOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:jurisdiction:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:jurisdiction:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:jurisdiction:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:jurisdiction:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="jurisdictionList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="主键" align="center" prop="id" />
      <el-table-column label="辖区名称" align="center" prop="jurisdictionName" />
      <el-table-column label="联系人" align="center" prop="name" />
      <el-table-column label="联系号码" align="center" prop="phone" />
      <el-table-column label="最小图片个数" align="center" prop="uploadImageMin" />
      <el-table-column label="城市" align="center" prop="cityId" :formatter="cityIdFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:jurisdiction:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:jurisdiction:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改辖区对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="650px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="辖区名称" prop="jurisdictionName">
          <el-input v-model="form.jurisdictionName" placeholder="请输入辖区名称" />
        </el-form-item>
        <el-form-item label="联系人" prop="name">
          <el-input v-model="form.name" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系号码" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入联系号码" />
        </el-form-item>
        <el-form-item label="最小图片数" prop="uploadImageMin" class="formlable">
          <el-input v-model="form.uploadImageMin" placeholder="请输入最小图片个数"/>
        </el-form-item>
        <el-form-item label="城市" prop="cityId" style="width: 50%;display: inline-block;">
          <el-select filterable v-model="form.cityId" placeholder="请选择城市">
            <el-option
              v-for="dict in cityIdOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
			  <el-form-item style="width: 40%;display: inline-block;">
			    <el-button @click="addDomain">新增高速</el-button>
			  </el-form-item>
        <el-form-item v-for="(domain, index) in domains" :label="'高速区间' + index" :key="domain.key">
        	<el-select filterable v-model="domain.expresswayName" placeholder="请选择高速名称" style="width: 180px;">
				    <el-option v-for="item in speedroad" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"></el-option>
				  </el-select>
			    <el-input v-model="domain.startKil" type="number" placeholder="开始公里数" style="width: 120px;"></el-input>
			    <el-input v-model="domain.endKil" type="number" placeholder="结束公里数" style="width: 120px;"></el-input>
			    <el-button @click.prevent="removeDomain(domain)">删除</el-button>
			  </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
	.el-dialog__body{
		max-height: 660px;
		overflow: auto;
	}
</style>
<script>
import { listJurisdiction, getJurisdiction, delJurisdiction, addJurisdiction, updateJurisdiction, exportJurisdiction } from "@/api/manage/jurisdiction";

export default {
  name: "Jurisdiction",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 辖区表格数据
      jurisdictionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 城市字典
      cityIdOptions: [],
      speedroad: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jurisdictionName: null,
        name: null,
        phone: null,
        cityId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jurisdictionName:[
          {required: true, message: '请填写辖区', trigger: 'blur'}
        ],
        name:[
          {required: true, message: '请输入联系人', trigger: 'blur'}
        ],
				uploadImageMin:[
          {required: true, message: '请输入最小图片个数', trigger: 'blur'}
        ],
				phone:[
          {required: true, message: '请输入手机号', trigger: 'blur'}
        ],
      },
      domains: [{
        expresswayName: "",
			  startKil: "",
			  endKil: ""
      }],
    };
  },
  created() {
    this.getList();
    this.getDicts("hn_city").then(response => {
      this.cityIdOptions = response.data;
    });
    this.getDicts("expressway").then(response => {
      this.speedroad = response.data;
    });
  },
  methods: {

    removeDomain(item) {
      var index = this.domains.indexOf(item)
      if (index !== -1) {
        this.domains.splice(index, 1)
      }
    },
    addDomain() {
      this.domains.push({
        expresswayName: "",
			  startKil: "",
			  endKil: ""
      });
    },
    /** 查询辖区列表 */
    getList() {
      this.loading = true;
      listJurisdiction(this.queryParams).then(response => {
        this.jurisdictionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 城市字典翻译
    cityIdFormat(row, column) {
      return this.selectDictLabel(this.cityIdOptions, row.cityId);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        jurisdictionName: null,
        name: null,
        phone: null,
        createTime: null,
        uploadImageMin: null,
        cityId: null,
      };
      this.domains = [{
        expresswayName: "",
			  startKil: "",
			  endKil: ""
      }]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加辖区";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getJurisdiction(id).then(response => {
        this.form = response.data;
        this.domains = response.data.jurisdictionScopeList;
        this.open = true;
        this.title = "修改辖区";
      });
    },
    /** 提交按钮 */
    submitForm() {
    	this.form.jurisdictionScopeList = this.domains;
    	console.log(this.form)
    	if(this.form.cityId == null){
    		this.$message.error('请选择城市');
    		return false;
    	}
    	var reg_tel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
    	if(!reg_tel.test(this.form.phone)){
    		this.$message.error('手机号格式不正确');
    		return false;
    	}
    	for(var i=0;i<this.form.jurisdictionScopeList.length;i++){
    		if(this.form.jurisdictionScopeList[i].startKil == '' || this.form.jurisdictionScopeList[i].endKil == ''){
    			this.$message.error('请将高速的开始公里数和结束公里数填写完整');
    			return false;
    		}
    	}
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
          	updateJurisdiction(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });        
          } else {
          	addJurisdiction(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });        
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除辖区编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delJurisdiction(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有辖区数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportJurisdiction(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    }
  }
};
</script>
